import { userstore } from "../stores/user";
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
//对axios进行基本分装
import axios from "axios";
//只有在setup里面才能用userouter 其他地方只能导入router
import router from '../router/index'
const httpaxios = axios.create({
    baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
    timeout: 10000
})
// axios请求拦截器
httpaxios.interceptors.request.use(config => {
    //很多接口都需要判断是否有token 来判断是否有权限获取、
    const userStore = userstore()
    const token = userStore.userinfo.token
    //如果有token 则将token拼接到请求头 安装后端的方式来拼接
    if (token) config.headers.Authorization = `Bearer ${token}`
    return config
}, e => Promise.reject(e))

// axios响应式拦截器
httpaxios.interceptors.response.use(res => res.data, e => {
    const userStore = userstore()
    ElMessage({
        type: 'error',
        message: e.response.data.message
    })
    if (e.response.status === 401) {
        userStore.clearuser()
        router.push('/login')
    }
    return Promise.reject(e)
})
export default httpaxios